package main

import (
	"google.golang.org/grpc"
	pb "grpc-demo/complex/proto"
	"log"
	"net"
	"strconv"
)

// StreamServerServer is the server API for StreamServer service.
type StreamServerServerImpl struct {
	pb.UnimplementedStreamServerServer
}

// 实现自定义的ListValue方法
func (s *StreamServerServerImpl) ListValue(req *pb.SimpleRequest, srv pb.StreamServer_ListValueServer) error {
	for i := 0; i < 5; i++ {
		// 服务端连续发送消息
		err := srv.Send(&pb.StreamResponse{
			StreamValue: req.Data + strconv.Itoa(i),
		})
		if err != nil {
			return err
		}
	}
	return nil
}

// 服务端流式grpc
func main() {
	// 监听本地端口
	listener, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	log.Println("50051 is listening")

	// 建立grpc服务器实例
	grpcServer := grpc.NewServer()

	// 在服务器中注册服务
	pb.RegisterStreamServerServer(grpcServer, &StreamServerServerImpl{})

	// 启动服务
	err = grpcServer.Serve(listener)
	if err != nil {
		log.Fatal(err)
	}
}
